﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;

namespace GZSolver
{
  class InitialConditionsFileReader
  {
    private Matrix datasetMatrix = null;
    private double[] bVector = null;
    private double epsilon = 0.0;

    public InitialConditionsFileReader(String filename)
    {
      if (filename == null)
      {
        throw new NullReferenceException("Filename string is null.");
      }
      if (!File.Exists(filename))
      {
        throw new FileNotFoundException(filename + " is not found. Initial conditions cannot be loaded.");
      }   
      this.ReadFile(filename);
    }

    private void ReadFile(String filename)
    {
      using (StreamReader fs = new StreamReader(filename))
      {
        // Should contain row number and column number (m n)
        string firstLine = fs.ReadLine();
        String[] firstLineArguments = firstLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        int matrixSize = Convert.ToInt32(firstLineArguments[0]);
        this.epsilon = Double.Parse(firstLineArguments[1], CultureInfo.InvariantCulture);
        Matrix matrix = new Matrix(matrixSize, matrixSize);
        double[] bVector = new double[matrixSize];
        // Read the rest
        String nextLine = null;
        for (int i = 0; i < matrixSize; i++)
        {
          nextLine = fs.ReadLine();
          String[] splittedNextString = nextLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
          for (int j = 0; j < matrixSize; j++)
          {
              matrix[i][j] = Double.Parse(splittedNextString[j], CultureInfo.InvariantCulture);
          }
          // Read b value after last a coefficient.
          bVector[i] = Convert.ToDouble(splittedNextString[matrixSize]);
        }
        datasetMatrix = matrix;
        this.bVector = bVector;
      }
    }

    public Matrix MatrixCoefficients
    {
      get
      {
        return this.datasetMatrix;
      }
    }

    public double[] BVector
    {
      get
      {
        return this.bVector;
      }
    }

    public double Epsilon
    {
        get
        {
            return this.epsilon;
        }
    }
  }
}
